package com.example.demo.controller;

import com.example.demo.entity.CourseBean;
import com.example.demo.entity.CourseChaptsBean;
import com.example.demo.entity.StudentBean;
import com.example.demo.service.CourseService;
import com.example.demo.service.StudentService;
import com.example.demo.util.PageEntity;
import com.example.demo.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/all")
    public List<StudentBean> get(){
        return studentService.all();
    }


    @PostMapping("/add")
    public ResponseEntity add(@RequestBody StudentBean studentBean){
        System.out.println(studentBean);
        Integer delete = studentService.add(studentBean);

        if(delete>0){
            return ResponseEntity.success("新增成功");
        }else{
            return ResponseEntity.failed("新增失败");
        }
    }


    @PostMapping("/edit")
    public ResponseEntity edit(@RequestBody StudentBean studentBean){
        System.out.println(studentBean);
        Integer update = studentService.update(studentBean);
        if(update>0){
            return ResponseEntity.success("编辑成功");
        }else{
            return ResponseEntity.failed("编辑失败");
        }
    }

    @GetMapping("/del")
    public ResponseEntity del(@RequestParam("id") Integer id){
        Integer delete = studentService.delete(id);
        if(delete>0){
            return ResponseEntity.success("删除成功");
        }else{
            return ResponseEntity.failed("删除失败");
        }

    }


    @GetMapping("/get/{id}")
    public  StudentBean getOne(@PathVariable Integer id){

        return studentService.one(id);
    }

    /**
     * 分页
     * @param pageNo
     * @param pageSize
     * @param address
     * @param name
     * @param sort 排序字段
     * @param order  排序方式  desc、asc
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity list(
            @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
            @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
            @RequestParam(value = "address",defaultValue = "") String address,
            @RequestParam(value = "name",defaultValue = "") String name,
            @RequestParam(value = "sort",defaultValue = "id") String sort,
            @RequestParam(value = "order",defaultValue = "desc") String order
    ){

        // 延迟加载  按需加载  懒加载
        //  不能进行关联查询  分为多条sql：
        //   主语句  select　＊　　ｆｒｏｍ　ｕｓｅｒ
        //   从语句 select * from level  where id=?

        String  sortOrder = sort+" "+order;
        PageEntity list = studentService.list(pageNo, pageSize, address, name, sortOrder);
        ResponseEntity<PageEntity> data = new ResponseEntity<>(200,null,list);
        // 按需加载
        return data;
    }
}
